package java8;

import java.util.NoSuchElementException;
import java.util.Optional;

import org.junit.Assert;
import org.junit.Test;

public class Optional_Tester {

	@Test
	public void test() {
		Assert.assertThrows(NullPointerException.class, () -> {
			Assert.assertNull(Optional.of(null));// of不接收null值
		});
		Assert.assertFalse(Optional.of(false).get());
		Assert.assertTrue(Optional.of(true).get());
		Assert.assertTrue(Optional.of(0).get() == 0);
		Assert.assertTrue(Optional.of(1).get() == 1);
		Assert.assertEquals(Optional.of("").get(), "");
		Assert.assertEquals(Optional.of("value").get(), "value");

		Assert.assertThrows(NoSuchElementException.class, () -> {
			Assert.assertNull(Optional.ofNullable(null).get());// ofNullable接收空值，但调用get前必须设置非null值。
		});
		Assert.assertFalse(Optional.ofNullable(false).get());
		Assert.assertTrue(Optional.ofNullable(true).get());
		Assert.assertTrue(Optional.ofNullable(0).get() == 0);
		Assert.assertTrue(Optional.ofNullable(1).get() == 1);
		Assert.assertEquals(Optional.ofNullable("").get(), "");
		Assert.assertEquals(Optional.ofNullable("value").get(), "value");

		Assert.assertFalse(Optional.ofNullable(null).isPresent());
		Assert.assertTrue(Optional.ofNullable(false).isPresent());
		Assert.assertTrue(Optional.ofNullable(true).isPresent());
		Assert.assertTrue(Optional.ofNullable(0).isPresent());
		Assert.assertTrue(Optional.ofNullable(1).isPresent());
		Assert.assertTrue(Optional.ofNullable("").isPresent());
		Assert.assertTrue(Optional.ofNullable("value").isPresent());

		final Optional<Integer> optional_null = Optional.ofNullable(null);
		final Optional<Integer> optional_0 = Optional.ofNullable(0);
		Assert.assertTrue(optional_null.orElse(1) == 1);
		Assert.assertTrue(optional_0.orElse(1) == 0);
		Assert.assertTrue(optional_null.orElseGet(() -> { return 1; }) == 1);
		Assert.assertTrue(optional_0.orElseGet(() -> { return 1; }) == 0);
		Assert.assertThrows(RuntimeException.class, () -> {
			Assert.assertTrue(optional_null.orElseThrow(() -> { return new RuntimeException(); }) == 1);
		});
		Assert.assertTrue(optional_0.orElseThrow(() -> { return new RuntimeException(); }) == 0);
	}

}
